using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.Linq;

namespace EntityKit.Editor
{
    public static class PrefabFinder
    {
        public const string PackageName = "com.lygame";
        public const string PrefabSearchFilter = "t:Prefab";

        public static GameObject FindEnginePrefab(string prefabName)
        {
            var candidates = AssetDatabase.FindAssets($"{PrefabSearchFilter} {prefabName}")
                .Select(AssetDatabase.GUIDToAssetPath)
                .Where(p => !string.IsNullOrEmpty(p)).Select(p => new PrefabCandidate
                {
                    Path = p,
                    Asset = AssetDatabase.LoadAssetAtPath<GameObject>(p)
                })
                .Where(x => x.Asset != null && x.Asset.name == prefabName).ToList();

            return FindByPriority(candidates);
        }

        private static GameObject FindByPriority(List<PrefabCandidate> candidates)
        {
            return candidates.FirstOrDefault(x => IsInPackage(x.Path, PackageName))?.Asset ??
                   candidates.FirstOrDefault()?.Asset;
        }

        public static bool IsInPackage(string path, string packageName)
        {
            return path.StartsWith($"Packages/{packageName}/") || path.Contains($"/{packageName}/");
        }


        private static void InstantiatePrefabAtCenter(string targetPrefab)
        {
            var prefab = FindEnginePrefab(targetPrefab);
            if (prefab == null)
            {
                Debug.LogError($"Can't find {targetPrefab} prefab in resources");
                return;
            }

            try
            {
                var instance = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
                if (instance == null)
                {
                    Debug.LogError($"Failed to instantiate {targetPrefab}");
                    return;
                }

                PlaceAtSceneCenter(instance);
            }
            catch (Exception e)
            {
                Debug.LogError($"Error instantiating {targetPrefab}: {e.Message}");
            }
        }

        public static void PlaceAtSceneCenter(GameObject instance)
        {
            if (SceneView.lastActiveSceneView == null) return;

            instance.transform.position = SceneView.lastActiveSceneView.pivot;
            SceneView.FrameLastActiveSceneView();
            Selection.activeObject = instance;
            EditorGUIUtility.PingObject(instance);
        }

        public class PrefabCandidate
        {
            public string Path { get; set; }
            public GameObject Asset { get; set; }
        }
    }
}